import axios, { AxiosResponse } from "axios"
import type { AxiosInstance, InternalAxiosRequestConfig } from "axios"
import type { FYRequestConfig } from "./type"

/**
 * 两个难点：
 *  1.拦截器进行精细控制
 *      > 全局拦截器
 *      > 实例拦截器
 *      >  单次请求拦截器
 *  2.响应结果类型处理（泛型）
 */

class HYRequest {
    instance: AxiosInstance
    // request实例 => axios的实例
    constructor(config: FYRequestConfig) {
        this.instance = axios.create(config)

        this.instance.interceptors.request.use(config => {
            console.log("全局请求成功的拦截")
            return config
        }, err => {
            console.log("全局请求失败的拦截")
        })
        this.instance.interceptors.response.use(res => {
            console.log("全局响应成功的拦截")
            return res.data
        }, err => {
            console.log("全局响应失败的拦截")
        })

        this.instance.interceptors.request.use(config.interceptors?.requestSuccessFn, config.interceptors?.requestFailFn)
        this.instance.interceptors.response.use(config.interceptors?.responseSuccessFn, config.interceptors?.responseFailFn)

    }
    // 封装网络请求方法
    request<T = any>(config: FYRequestConfig<T>) {
        if (config.interceptors?.requestSuccessFn) {
            config = config.interceptors.requestSuccessFn(config as InternalAxiosRequestConfig)
        }
        // this.instance.request(config)
        return new Promise<T>((resolve, reject) => {
            this.instance.request<any, T>(config).then(res => {
                if (config.interceptors?.responseSuccessFn) {
                    res = config.interceptors.responseSuccessFn(res)
                }
                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    }
    get<T = any>(config: FYRequestConfig<T>) {
        return this.request({ ...config, method: "get" })
    }
    post<T = any>(config: FYRequestConfig<T>) {
        return this.request({ ...config, method: "post" })
    }

}

export default HYRequest